package GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableRowSorter;
import javax.swing.text.BadLocationException;
import javax.swing.text.MaskFormatter;
import net.sourceforge.jdatepicker.JDateComponentFactory;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;
import CommonGui.NotEdditibleTable;
import DataObjects.ConstantObjects;
import DataObjects.TotalHoursInMonth;
import DataObjects.TotalHoursInMonthAccess;
import Messages.MessageAddCommentAboutOverHrs;
import Messages.MessageAddOrUpdateWorkingHoursFromDoh;
import Messages.MessageAddWorkingHoursReply;
import Messages.MessageRemoveCommentAboutOverHrs;
import Messages.MessageSavingReply;
import Messages.MessageShowAllWorkHours;
import Messages.MessageShowAllWorkHoursReply;
import Reports.DataForPrintWorkingHours;


/**
 * Class for creation panel that includes JTable with work hours of selected employee by range of date(ID,name,date,clock in,clock out)
 * @author jeka
 *
 */
public class PfDoh_work_hoursAdmin extends JPanel{  
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3028513778928149361L;

	private MainMenu mainMenu;
	
	private NotEdditibleTable dtm; 
	private JTable tbl;
	
	public Vector<Vector> allHours;
	public Vector<Vector> allHours2;
	private Vector<Vector> allHoursOfThisMonth;
	// ID,name emp,date,clock_in,clock_out
	private Vector <String> tblheader;
	private Vector<String> selectedRowVec=null;
	
	private JLabel workDayLbl;
	private JLabel workDaysLbl;
	private JLabel workDaysLbl2;
	private JLabel totalHrsLbl;
	
    private int	vecflag=0;
	private String selectedRole;
	private VKTextField textField_name;            
	private VKTextField textField_date;
	private VKTextField nameTF;
	private VKFormattedTextField timeEnterTF;
	private VKFormattedTextField timeExitTF;
	private JDatePickerImpl newWorkDate;
	private String day1;
	private String year1;
	private String month1;
	private JComboBox roleBox;
	private JPanel checkWorkDayPanel;
	private JPanel changeWorkDayPanel;
	private JPanel searchHours;
	private JPanel TotalHours;
	private JPanel insertWorkDayPanel;
	public int x;
	private int y;
	private Dimension screenSize;
		
	public PfDoh_work_hoursAdmin(MainMenu mm,Vector<Vector> workHours)
	{
		super();
		screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		x=screenSize.width;
		y=screenSize.height;
		
		this.setLayout(new BorderLayout());
		this.mainMenu=mm;
		this.allHoursOfThisMonth=workHours; 		//for button getWorkDaysButton (חודש נוכחי)
		this.allHours=workHours;
		this.allHours2=workHours;
		
	
		 
		initiliaze();
	}	
	
	
	private void initiliaze()
	{
		
		
		JScrollPane scrollPane = new JScrollPane(getTblHours());
		this.add(scrollPane,BorderLayout.CENTER);
		this.add(getSearchMonths(),BorderLayout.NORTH);
		this.add(getUnderPanel(),BorderLayout.SOUTH);
	}
	
	/**
	 * Method for creation JTable tbl that consists of work hours of selected employee by range of date(ID,name,date,clock in,clock out)
	 * @return tbl
	 */
	public JTable getTblHours()
	{
		tblheader=new Vector<String>();
		tblheader.add("ID");
		tblheader.add("שם עובד");
		tblheader.add("תאריך");
		tblheader.add("שעת כניסה");
		tblheader.add("שעת יציאה");
		tblheader.add("הערות");
		  
		dtm=new NotEdditibleTable(allHours,tblheader);	 
		 
		tbl = new JTable(dtm);
		DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
		centerRenderer.setHorizontalAlignment( JLabel.CENTER );
		for(int x=0;x<5;x++){
			tbl.getColumnModel().getColumn(x).setCellRenderer( centerRenderer );
	        }
		
		tbl.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		tbl.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
		tbl.setFont(new Font("David", Font.BOLD, 16));
		tbl.getTableHeader().setFont( new Font( "Arial" , Font.BOLD, 17 ));
		tbl.getTableHeader().setBackground(new Color(173,216,230));
		tbl.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); 
	    tbl.setRowHeight(30);
		tbl.setFillsViewportHeight(true);
        tbl.setGridColor(new Color(25, 25, 112));
        tbl.setBackground(new Color(250, 235, 215));
        tbl.setForeground(new Color(0, 0, 0));
        tbl.setAutoCreateRowSorter(true);
                 
        tbl.addMouseListener(new MouseAdapter() {
			   public void mouseClicked(MouseEvent e) {
				   JTable target = (JTable)e.getSource();
			       int row = target.getSelectedRow();
			       if (e.getClickCount() == 1) {
			       if(row!=-1)
			       {			    	 
				       selectedRowVec=(Vector<String>) dtm.getDataVector().get(row);		     
				      
			       }
			     }
			     
			     if (e.getClickCount() == 2 && row!=-1){
			    	 addChangeWorkDayPanel();
			         }
			     }
			   
			 });
                
        return tbl;
	}
	
	/**
	 * Method for creation JPanel searchHours that includes  ComboBox filter by months that it gets from
	 *   method "getMonthCB" for choose another months  in which employee want to see their work days and work hours.
	 *   In addition panel "searchHours" includes button "חודש נוכחי" that it gets from method getWorkDaysButton for 
	 *   return to current month and label that show quantity of work days of any month that employee choose.
	 * @return
	 */
	private JPanel getSearchMonths()
	{
		searchHours=new JPanel ();
	    searchHours.setBackground(new Color(255, 245, 238));
	    searchHours.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
	    searchHours.add(getMonthCB());
	    searchHours.add(getMonthLbl());
	    searchHours.add(getWorkDaysButton());
	  //  searchHours.add(getWorkDay(allHours));
	 //   searchHours.add(getWorkDays());
	//---------------------------
	    
		return searchHours;
	}
	
	
	//--------------------------------------------------------------------
		private JPanel getUnderPanel()            
		{
		 
		    TotalHours=new JPanel ();
		    TotalHours.setBackground(new Color(255, 245, 238));
		    TotalHours.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));    //change
		    TotalHours.add(getTotalHours(allHours));
		    TotalHours.add(getWorkDays2());
		    TotalHours.add(getWorkDay(allHours));
		    TotalHours.add(getWorkDays());
			 
	    	//TotalHours.validate();
			 
			return TotalHours;
		}
		
		
 
	
	/**
	 * Method for creation JComboBox monthsCB for choosing month  in which user want to see their work days
	 * @return monthsCB
	 */
	private JComboBox getMonthCB()
	{
		JComboBox monthsCB=new JComboBox(new ConstantObjects().getMonths());
		monthsCB.addActionListener(new java.awt.event.ActionListener() 
	  	{
			public void actionPerformed(java.awt.event.ActionEvent e) {
				
			   JComboBox roleBox = (JComboBox)e.getSource();
			   selectedRole = (String)roleBox.getSelectedItem(); 
	           Vector<Vector> allHoursNew = new  Vector<Vector>();
	           
	           MessageShowAllWorkHours msgShowHours=new MessageShowAllWorkHours((String)allHours2.get(0).get(0),selectedRole );
	          
				try {
					mainMenu.ms.client.sendToServer(msgShowHours);
			        MessageShowAllWorkHoursReply resultHours=(MessageShowAllWorkHoursReply)mainMenu.ms.client.GetMessage();
					allHoursNew=resultHours.getEmployeeHours();
					 
					dtm.setDataVector(allHoursNew, tblheader);     
					 
					allHours=allHoursNew;                              
					//searchHours.remove(workDayLbl);
					//searchHours.remove(workDaysLbl);
					 
					TotalHours.remove(workDayLbl);
					TotalHours.remove(workDaysLbl);
					TotalHours.remove(workDaysLbl2);
					TotalHours.remove(totalHrsLbl);
					TotalHours.add(getTotalHours(allHours)); 
					TotalHours.add(getWorkDays2());
					TotalHours.add(getWorkDay(allHours));
					TotalHours.add(getWorkDays());
					
					TotalHours.validate();
					 
				    }
				catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			  
				} 
		});	
		return monthsCB;
	}
	

	

	/**
	 * Method for creation JLabel monthLbl to JComboBox monthsCB(used by method getMonthCB)
	 * @return monthLbl
	 */
	private JLabel getMonthLbl()
	{
		JLabel monthLbl=new JLabel("     חודש  :   ");
		monthLbl.setFont(new Font("Tahoma", Font.PLAIN, 13));
		return monthLbl;
	}
	
	/**
	 * Two methods for creation two labels :the first for  show quantity of work days in any
	 *  month and the second for  name of the first(כמות ימי עבודה בחודש זה)
	 * @return workDaysLbl,workDayLbl
	 */
	private JLabel getWorkDays()
	{
	    workDaysLbl=new JLabel("בתקופת ניתוח הנוכחות  ");
		workDaysLbl.setFont(new Font("Tahoma", Font.PLAIN, 16));
		return workDaysLbl;
	}
	
	private JLabel getWorkDays2()
	{
	    workDaysLbl2=new JLabel(" ימי עבודה  ");
		workDaysLbl2.setFont(new Font("Tahoma", Font.PLAIN, 16));
		return workDaysLbl2;
	}
	
	private JLabel getTotalHours(Vector<Vector> allHours3) 
	{ 
		TotalHoursInMonth totInMonth = new TotalHoursInMonth(allHours3); 
		
	    try {
			 totInMonth.CalculateMonthHours();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}                
	 
	    
	    totalHrsLbl=new JLabel(" שבהם "+ totInMonth.getHoursOfMonth()+ " שעות " + totInMonth.getMinutesOfMonth()+ " דקות " + totInMonth.getSecondsOfMonth()+ " שניות ");
	    
       // totalHrsLbl=new JLabel(" סהכ שעות עבודה "+ totInMonth.CalculateMonthHours());  
	    totalHrsLbl.setFont(new Font("Tahoma", Font.PLAIN, 16));
		return totalHrsLbl;
	}
	
	 
	
	private JLabel getWorkDay(Vector<Vector> workHours)
	{
	 
		int numOFdays=0;
		
		if(workHours.size()>0)
		{
		   numOFdays=1;		 
		 
		for(int i=1;i<workHours.size()-1;i++)
		{
			if(!workHours.get(i).get(2).equals(workHours.get(i-1).get(2))) {	numOFdays++;	} 
			
			
		}
		}
	    workDayLbl=new JLabel(Integer.toString(numOFdays));
		workDayLbl.setFont(new Font("Tahoma", Font.BOLD, 15));
		return workDayLbl;
	}
	
	/**
	 * Method for creation JButton workDayBut that return user to current month(show work days of current month)
	 * @return workDayBut
	 */
	private JButton getWorkDaysButton()
	{
		
		JButton workDayBut=new JButton("חודש נוכחי");
		workDayBut.setFont(new Font("Tahoma", Font.PLAIN, 13));
		workDayBut.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
								
			//	dtm.setDataVector(allHoursOfThisMonth, tblheader); 
				  
		   //   (JComboBox)e.setSource("-");
				  Date dat = new Date();
				  DateFormat dfmonth = new SimpleDateFormat("MM");
				  String   month = dfmonth.format(dat); 
				    
				  Vector<Vector> allHoursNew2 = new  Vector<Vector>();
		        
		           MessageShowAllWorkHours msgShowHours=new MessageShowAllWorkHours((String)allHours2.get(0).get(0), month );
		          
		           try {
						mainMenu.ms.client.sendToServer(msgShowHours);
				        MessageShowAllWorkHoursReply resultHours=(MessageShowAllWorkHoursReply)mainMenu.ms.client.GetMessage();
						allHoursNew2=resultHours.getEmployeeHours();
						 
						dtm.setDataVector(allHoursNew2, tblheader);     
						//change TableModel for repaint  table with another month
						allHoursOfThisMonth=allHoursNew2;       //j
						    
					    	TotalHours.remove(workDayLbl);
							TotalHours.remove(workDaysLbl);
							TotalHours.remove(workDaysLbl2);
							TotalHours.remove(totalHrsLbl);
					    	TotalHours.add(getTotalHours(allHoursOfThisMonth)); 
							TotalHours.add(getWorkDays2());
							TotalHours.add(getWorkDay(allHoursOfThisMonth));
							TotalHours.add(getWorkDays());
							
							TotalHours.validate();
						  
		           }
					catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} 
				  
				  
			}
		});
	
		return workDayBut;
	}	
	
	
	public void addInsertWorkDayPanel()
	{
		if(insertWorkDayPanel!=null) this.remove(insertWorkDayPanel);
		if(changeWorkDayPanel!=null) this.remove(changeWorkDayPanel);
		this.add(getInsertWorkDayPanel(),BorderLayout.EAST);
		mainMenu.getContentPane().validate();
	}
	
	/**
	 * Method for creation JPanel insertWorkDayPanel(panel that open from right side of the doh)that consists of 
	 * 3 panels and needs to addition  new work day to employee if he forgot to press Enter button when he came to work.
	 * Only manager can to do this action  
	 * @return insertWorkDayPanel
	 */
	private JPanel getInsertWorkDayPanel()
	{
		insertWorkDayPanel = new JPanel();
		insertWorkDayPanel.setBackground(new Color(255, 250, 205));
		insertWorkDayPanel.setLayout(new BoxLayout(insertWorkDayPanel, BoxLayout.Y_AXIS));
		insertWorkDayPanel.add( getInsertInfoPanel());
		insertWorkDayPanel.add( getCheckWorkDayPanel());
		insertWorkDayPanel.add(getButtonsPanel());
		return insertWorkDayPanel;
	}
	
	/**
	 * Method for creation JPanel insertWorkDayPanel that consists of fields that need to be filled with details 
	 * of new work day(clock in,clock out and date)
	 * @return insertWorkDayPanel
	 */
	private JPanel getInsertInfoPanel()
	{
		
		JPanel insertWorkDayPanel=new JPanel();
		insertWorkDayPanel.setBackground(new Color(255, 250, 205));
		insertWorkDayPanel.setForeground(new Color(0, 0, 0));
		insertWorkDayPanel.setLayout(new SpringLayout());
		textField_name=new VKTextField(mainMenu);
		textField_name.setHorizontalAlignment(JTextField.RIGHT);
		textField_name.setEditable(false);
		  
		textField_name.setText((String) allHours2.get(0).get(1));
		textField_name.setFont(new Font("Tahoma", Font.BOLD, 14));
	    JLabel nameLbl = new JLabel("שם העובד :", JLabel.TRAILING);
	    nameLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
	    nameLbl.setForeground(new Color(25, 25, 112));
	    nameLbl.setLabelFor(textField_name);
	    insertWorkDayPanel.add(textField_name);
	    insertWorkDayPanel.add(nameLbl);
		newWorkDate=getOrderDate();
		newWorkDate.setFont(new Font("Tahoma", Font.BOLD, 14));
		JLabel dateLbl = new JLabel("תאריך יום עבודה :", JLabel.TRAILING);
		dateLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		dateLbl.setForeground(new Color(25, 25, 112));
		dateLbl.setLabelFor(newWorkDate);
		insertWorkDayPanel.add(newWorkDate);
		insertWorkDayPanel.add(dateLbl);
						
		 MaskFormatter mask = null;
	        try {
	            //
	            // Create a MaskFormatter for accepting phone number, the # symbol accept
	            // only a number. We can also set the empty value with a place holder
	            // character.
	            //
	            mask = new MaskFormatter("##:##:##");
	            mask.setPlaceholderCharacter('_');
	        } catch (ParseException e) {
	            e.printStackTrace();
	        }
	        
		       timeEnterTF = new VKFormattedTextField(mainMenu,mask);
		       timeEnterTF.setColumns(6);
		       timeEnterTF.setText("000000");
		       timeEnterTF.setFont(new Font("Tahoma", Font.BOLD, 14));
		       JLabel timeEnterLbl = new JLabel("שעת כניסה :", JLabel.TRAILING);
		       timeEnterLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		       timeEnterLbl.setForeground(new Color(25, 25, 112));
		       timeEnterLbl.setLabelFor(timeEnterTF);
		       insertWorkDayPanel.add(timeEnterTF);
		       insertWorkDayPanel.add(timeEnterLbl);
			   timeExitTF = new VKFormattedTextField(mainMenu,mask);
			   timeExitTF.setColumns(6);
			   timeExitTF.setText("000000");
			   timeExitTF.setFont(new Font("Tahoma", Font.BOLD, 14));
		       JLabel timeExitLbl = new JLabel("שעת יציאה :", JLabel.TRAILING);
		       timeExitLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		       timeExitLbl.setForeground(new Color(25, 25, 112));
		       timeExitLbl.setLabelFor(timeExitTF);
		       insertWorkDayPanel.add(timeExitTF);
		       insertWorkDayPanel.add(timeExitLbl);
						 
			SpringUtilities.makeCompactGrid(insertWorkDayPanel,4, 2, //rows, cols
				     20, 20, //initX, initY
				       20, 20); //xPad, yPad
			
					
		return insertWorkDayPanel;
				
			}
	
	
	/**
	 * Method for creation JPanel buttonsPanel that includes buttons to control of new work day
	 * which user wants to add(save,new and cancel)
	 * @return buttonsPanel
	 */
	private JPanel getButtonsPanel()
	{
		JPanel buttonsPanel=new JPanel();
		buttonsPanel.setBackground(new Color(255, 250, 205));
		buttonsPanel.setForeground(new Color(0, 0, 0));
		buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));
		buttonsPanel.add(getBtnSave());
		buttonsPanel.add(Box.createHorizontalStrut(10));
		buttonsPanel.add(getBtnNewWorkDay());
		buttonsPanel.add(Box.createHorizontalStrut(10));
		buttonsPanel.add(getBtnCancel());
		buttonsPanel.setPreferredSize(new Dimension(500,500));
		return buttonsPanel;
	}
	
	/**
	 * Method for creation JButton btnCancel that close panel getInsertInfoPanel
	 * @return btnCancel
	 */
	private JButton getBtnCancel()
	{
		JButton btnCancel=new JButton("סגור");
		btnCancel.setFont(new Font("Tahoma", Font.BOLD, 14));
		btnCancel.addActionListener(new java.awt.event.ActionListener() 
		   {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{	
				
				((JButton)e.getSource()).getParent().getParent().getParent().remove(((JButton)e.getSource()).getParent().getParent());
				
				mainMenu.getContentPane().validate();
				
				
			}
			
			
		});
		return btnCancel;
	}
	
	
	
	/**
	 * Method for creation JButton btnNewWorkDay that open new panel getInsertInfoPanel for addition
	 * new work day 
	 * @return btnNewWorkDay
	 */
	private JButton getBtnNewWorkDay()
	{
		JButton btnNewWorkDay=new JButton("יום עבודה חדש");
		btnNewWorkDay.setFont(new Font("Tahoma", Font.BOLD, 14));
		btnNewWorkDay.addActionListener(new java.awt.event.ActionListener() 
		   {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{
				addInsertWorkDayPanel();			
			}
		});
		return btnNewWorkDay;
	}
	
	/**
	 * Method for creation JButton btnSave that saves new work day after checking of correctness input
	 * @return btnSave
	 */
	private JButton getBtnSave()
	{
		JButton btnSave=new JButton("שמור");
		btnSave.setFont(new Font("Tahoma", Font.BOLD, 14));
		btnSave.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				
				JButton savebutt=(JButton) e.getSource();	
				checkWorkDayPanel.removeAll();
				Vector<String> checkingResult=inputCheck();
				int size=checkingResult.size();                          
				if(size==0)
				{
					Vector<String> workDay =new Vector<String>();
					int year=newWorkDate.getModel().getYear();
					int month=newWorkDate.getModel().getMonth()+1;
					int day=newWorkDate.getModel().getDay();
					workDay.add((String) allHours.get(0).get(0));
					
					workDay.add(Integer.toString(year)+"-"+Integer.toString(month)+"-"+Integer.toString(day));
					 
					if(!timeEnterTF.getText().isEmpty()){
					workDay.add(timeEnterTF.getText());
					}
					else JOptionPane.showMessageDialog(null,"נא לרשום שעת כניסה");
					if(!timeExitTF.getText().isEmpty()){
					workDay.add(timeExitTF.getText());
					}else JOptionPane.showMessageDialog(null,"נא לרשום שעת יציאה");
					 					  
					  try {
						  if(!timeEnterTF.getText(0, 2).equals("__")){ 
							  int in_hours=Integer.parseInt(timeEnterTF.getText(0, 2));
							  if(in_hours>23||in_hours<0) {JOptionPane.showMessageDialog(null,"שעת כניסה לא תקינה");  vecflag=1;}
								
							  }
						  else { JOptionPane.showMessageDialog(null,"שעת כניסה לא תקינה"); vecflag=1;}
						  if(!timeEnterTF.getText(3, 2).equals("__")){ 
							  int in_minuts=Integer.parseInt(timeEnterTF.getText(3, 2));
							  if(in_minuts>59||in_minuts<0) {JOptionPane.showMessageDialog(null,"דקת כניסה לא תקינה"); vecflag=1;}
								  
						  }
						  else {   vecflag=1;}
						  if(!timeEnterTF.getText(6, 2).equals("__")){ 
							  int in_seconds=Integer.parseInt(timeEnterTF.getText(6, 2));
							  if(in_seconds>59||in_seconds<0) {JOptionPane.showMessageDialog(null,"שנית כניסה לא תקינה"); vecflag=1;}
								  
						  }
						  else {   vecflag=1;}
						  if(!timeExitTF.getText(0, 2).equals("__")){ 
							  int out_hours=Integer.parseInt(timeExitTF.getText(0, 2));
							  if(out_hours>23||out_hours<0) {JOptionPane.showMessageDialog(null,"שעת יציאה לא תקינה"); vecflag=1;}
								
						  }
						  else {JOptionPane.showMessageDialog(null,"שעת יציאה לא תקינה");  vecflag=1;}
						  if(!timeExitTF.getText(3, 2).equals("__")){ 
							  int out_minuts=Integer.parseInt(timeExitTF.getText(3, 2));
							  if(out_minuts>59||out_minuts<0){ JOptionPane.showMessageDialog(null,"דקת יציאה לא תקינה"); vecflag=1;}
								
							  }
						  else {  vecflag=1;}
						  if(!timeExitTF.getText(6, 2).equals("__")){ 
							  int out_seconds=Integer.parseInt(timeExitTF.getText(6, 2));
							  if(out_seconds>59||out_seconds<0){ JOptionPane.showMessageDialog(null,"שנית יציאה לא תקינה"); vecflag=1;}
								 
						  }
						  else {   vecflag=1;}
					 
						  workDay.add(String.valueOf(0));        // INSERT NEW DAY
						
					} catch (BadLocationException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					 
					  if(vecflag!=1)
					  {
						  MessageAddOrUpdateWorkingHoursFromDoh msgNewHours= new MessageAddOrUpdateWorkingHoursFromDoh(workDay);
					
					 try {
							mainMenu.ms.client.sendToServer(msgNewHours);
							MessageSavingReply result=(MessageSavingReply)mainMenu.ms.client.GetMessage();
							MessageAddWorkingHoursReply result1 = (MessageAddWorkingHoursReply)mainMenu.ms.client.GetMessage(); 
						  
							//calculate the work hours of this day and this month
							
							if (result.getResult()==1) 
							{
								//AccessClockInClockOut access=new AccessClockInClockOut(mainMenu,result1.getWorkHours(),result1.getWorkHours());
								TotalHoursInMonthAccess totHrs = new TotalHoursInMonthAccess(result1.getWorkHours());
							 
							   	 try {
									totHrs.CalculateMonthHours();
								} catch (ParseException e2) {
									// TODO Auto-generated catch block
									e2.printStackTrace();
								}
							   	
							   int totHrsDay=Integer.parseInt(totHrs.getHoursOfMonth());
								if(totHrsDay>12)
						    		
					    		{
									workDay.add("check num. of hours");          //יש חריגה בכמות שעות בתאריך הזה
					    			 
									JOptionPane.showMessageDialog(null,"יש חריגה בכמות שעות בתאריך הזה"); 
					    		}
					    		else{ workDay.add("null"); }
								
								if(!workDay.get(5).equals("null"))          // write comment about exceed number of working hours 
						    		
					    		{
									 
									MessageAddCommentAboutOverHrs mess1 = new MessageAddCommentAboutOverHrs(workDay, 0);  
									mess1.setEmpDetails(workDay);       
								 
								    //send to server(empID,data,time) of  employee 
								try {
									mainMenu.ms.client.sendToServer(mess1);
									 
									
									
								} catch (IOException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
								
								
					    		}
																								
							JLabel goodLbl2=new JLabel("יום עבודה חדש נשמר בהצלחה");
							goodLbl2.setFont(new Font("Tahoma", Font.BOLD, 11));
							goodLbl2.setForeground(Color.blue);
							checkWorkDayPanel.add(goodLbl2);
							//DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
							//Date date = new Date();
							
							MessageShowAllWorkHours msgAllHours=new MessageShowAllWorkHours((String) allHours.get(0).get(0),Integer.toString(month));
							mainMenu.ms.client.sendToServer(msgAllHours);
							MessageShowAllWorkHoursReply resultHours=(MessageShowAllWorkHoursReply)mainMenu.ms.client.GetMessage();
							Vector<Vector> workHours=resultHours.getEmployeeHours();
							allHours.removeAllElements();
							for(int i=0 ; i<workHours.size();i++)
							{
								allHours.add(workHours.get(i));
							}
							 
							tbl.repaint();
							tbl.validate();
						 
							//=--------------------------------
							TotalHours.remove(workDayLbl);
							TotalHours.remove(workDaysLbl);
							TotalHours.remove(workDaysLbl2);
							TotalHours.remove(totalHrsLbl);
							TotalHours.add(getTotalHours(allHours));            
							TotalHours.add(getWorkDays2());
							TotalHours.add(getWorkDay(allHours));
							TotalHours.add(getWorkDays());
							
							TotalHours.validate();
							
							mainMenu.getContentPane().validate();
							savebutt.setEnabled(false);
							
							}
							else
							{
								JLabel wrongLbl2=new JLabel("בעיית תקשורת . הנתונים לא נשמרו");
								wrongLbl2.setFont(new Font("Tahoma", Font.BOLD, 15));
								wrongLbl2.setForeground(Color.red);
								checkWorkDayPanel.add(wrongLbl2);
							}
							
														
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					  }//if
					  else                                //wrong input-print all errors on check_panel
						{
							
							JLabel wrongLbl=new JLabel("הנתונים אינם תקינים :");
							wrongLbl.setFont(new Font("Tahoma", Font.BOLD, 13));
							wrongLbl.setForeground(Color.red);
							checkWorkDayPanel.add(wrongLbl);
							for(int i=0;i<size;i++)
							{
								JLabel error=new JLabel(checkingResult.get(i));
								error.setForeground(Color.red);
								checkWorkDayPanel.add(error);
							}
						}
					  vecflag=0;
					  
				}
								
		 
				
				mainMenu.getContentPane().validate();
				}
		});
		
		return btnSave;
	}
		
		
	public void addChangeWorkDayPanel()
	{
		if(insertWorkDayPanel!=null) this.remove(insertWorkDayPanel);
		if(changeWorkDayPanel!=null) this.remove(changeWorkDayPanel);
		this.add(getChangeWorkDayPanel(),BorderLayout.EAST);
		mainMenu.getContentPane().validate();
	}
	
	/**
	 * Method for creation JPanel changeWorkDayPanel(panel that open from right side of the doh)that consists of 
	 * 3 panels and needs to change details of the new work day of employee that forgot to press Enter button when he came to work.
	 * Only manager can to do this action  
	 * @return changeWorkDayPanel
	 */
	private JPanel getChangeWorkDayPanel()
	{
		changeWorkDayPanel = new JPanel();
		changeWorkDayPanel.setBackground(new Color(255, 250, 205));
		changeWorkDayPanel.setLayout(new BoxLayout(changeWorkDayPanel, BoxLayout.Y_AXIS));
		changeWorkDayPanel.add( getChangeInfoPanel());
		changeWorkDayPanel.add( getCheckWorkDayPanel());
		changeWorkDayPanel.add(getButtonsPanel2());
		return changeWorkDayPanel;
	}
	
	/**
	 * Method for creation JPanel changeInfoPanel that consists of fields that filled with details 
	 * of selected work day(clock in,clock out and date) and user can change it
	 * @return changeInfoPanel
	 */
	private JPanel getChangeInfoPanel()
	{
		JPanel changeInfoPanel=new JPanel();
		changeInfoPanel.setBackground(new Color(255, 250, 205));
		changeInfoPanel.setForeground(new Color(0, 0, 0));
		changeInfoPanel.setLayout(new SpringLayout());
		nameTF=new VKTextField(mainMenu);
		nameTF.setHorizontalAlignment(JTextField.RIGHT);
		nameTF.setEditable(false);
		nameTF.setFont(new Font("Tahoma", Font.BOLD, 14));
						
	    if(selectedRowVec!=null&&!selectedRowVec.isEmpty()) { nameTF.setText(selectedRowVec.get(1));  }
		//else { nameTF.setText(selectedRowVec.get(1));  }
	    JLabel nameLbl = new JLabel("שם העובד :", JLabel.TRAILING);
	    nameLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
	    nameLbl.setForeground(new Color(25, 25, 112));
	    nameLbl.setLabelFor(nameTF);
	    changeInfoPanel.add(nameTF);
	    changeInfoPanel.add(nameLbl);
		
	    textField_date=new VKTextField(mainMenu);
	    textField_date.setHorizontalAlignment(JTextField.RIGHT);
	    textField_date.setEditable(false);
	    textField_date.setFont(new Font("Tahoma", Font.BOLD, 14));
	     
	    if(selectedRowVec!=null&&!selectedRowVec.isEmpty()) {textField_date.setText(selectedRowVec.get(2));  }
		 	   //  selectedRowVec!=null  trouble
	    JLabel dateLbl = new JLabel("תאריך יום עבודה :", JLabel.TRAILING);
	    dateLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
	    dateLbl.setForeground(new Color(25, 25, 112));
	    dateLbl.setLabelFor(textField_date);
	    changeInfoPanel.add(textField_date);
	    changeInfoPanel.add(dateLbl);
				
		 MaskFormatter mask = null;
	        try {
	           
	            mask = new MaskFormatter("##:##:##");
	            mask.setPlaceholderCharacter('_');
	        } catch (ParseException e) {
	            e.printStackTrace();
	        }
	      
	        timeEnterTF = new VKFormattedTextField(mainMenu,mask);
	        timeEnterTF.setColumns(6);
	        if(selectedRowVec!=null&&!selectedRowVec.isEmpty()) {  timeEnterTF.setText(selectedRowVec.get(3)); }
	            else { JOptionPane.showMessageDialog(null,"נא לבחור שורה מתאימה"); }
	     
	           timeEnterTF.setFont(new Font("Tahoma", Font.BOLD, 14));
		       JLabel timeEnterLbl = new JLabel("שעת כניסה :", JLabel.TRAILING);
		       timeEnterLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		       timeEnterLbl.setForeground(new Color(25, 25, 112));
		       timeEnterLbl.setLabelFor(timeEnterTF);
		       changeInfoPanel.add(timeEnterTF);
		       changeInfoPanel.add(timeEnterLbl);
						
		       timeExitTF = new VKFormattedTextField(mainMenu,mask);
		       timeExitTF.setColumns(6);
		       if(selectedRowVec!=null&&!selectedRowVec.isEmpty()) {  timeExitTF.setText(selectedRowVec.get(4));  }
		       timeExitTF.setFont(new Font("Tahoma", Font.BOLD, 14));
		       JLabel timeExitLbl = new JLabel("שעת יציאה :", JLabel.TRAILING);
		       timeExitLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		       timeExitLbl.setForeground(new Color(25, 25, 112));
		       timeExitLbl.setLabelFor(timeExitTF);
		       changeInfoPanel.add(timeExitTF);
		       changeInfoPanel.add(timeExitLbl);
					   			
			SpringUtilities.makeCompactGrid(changeInfoPanel,4, 2, //rows, cols
				     20, 20, //initX, initY
				       20, 20); //xPad, yPad
				
		return changeInfoPanel;
			
	}
	
	private JPanel getCheckWorkDayPanel()
	{
		checkWorkDayPanel=new JPanel();
		checkWorkDayPanel.setLayout(new BoxLayout(checkWorkDayPanel, BoxLayout.Y_AXIS));
		checkWorkDayPanel.setAlignmentX(CENTER_ALIGNMENT);
		return checkWorkDayPanel;
	}
	
	/**
	 * Method for creation JPanel buttonsPanel that includes buttons to control of the work day
	 * which user wants to change(save,new and cancel)
	 * @return buttonsPanel
	 */
	private JPanel getButtonsPanel2()
	{
		JPanel buttonsPanel=new JPanel();
		buttonsPanel.setBackground(new Color(255, 250, 205));
		buttonsPanel.setForeground(new Color(0, 0, 0));
		buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));
		buttonsPanel.add(getBtnSave2());
		buttonsPanel.add(Box.createHorizontalStrut(10));
		//buttonsPanel.add(getBtnNewWorkDay());
		buttonsPanel.add(Box.createHorizontalStrut(10));
		buttonsPanel.add(getBtnCancel());
		buttonsPanel.setPreferredSize(new Dimension(500,500));
		return buttonsPanel;
	}
	

	/**
	 * Method for creation JButton getBtnSave2 that saves new work day after checking of correctness input
	 * @return getBtnSave2
	 */
	private JButton getBtnSave2()
	{
		JButton btnSave=new JButton("עדכן");
		btnSave.setFont(new Font("Tahoma", Font.BOLD, 14));
		btnSave.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				JButton savebutt=(JButton) e.getSource();	
				checkWorkDayPanel.removeAll();
				Vector<String> checkingResult=inputCheck();
				int size=checkingResult.size();                          
				if(size==0)
				{
				//	JLabel goodLbl=new JLabel("כל הנתונים תקינים");
				//	goodLbl.setFont(new Font("Tahoma", Font.BOLD, 13));
				//	goodLbl.setForeground(Color.blue);
				//	checkWorkDayPanel.add(goodLbl);
					Vector<String> workDay =new Vector<String>();
					 	
					try {
					
						 year1 = textField_date.getText(0,4);
						if(year1=="null"){ JOptionPane.showMessageDialog(null,"נא לרשום שנה"); 
						vecflag=1;}
						
						//if(!textField_date.getText(5,2).isEmpty()){
						month1=textField_date.getText(5,2);
						if(month1=="null"){ JOptionPane.showMessageDialog(null,"נא לרשום חודש"); 
						vecflag=1;}
						 
						day1=textField_date.getText(8,2);
						if(day1=="null"){  JOptionPane.showMessageDialog(null,"נא לרשום יום"); 
						vecflag=1;}
					 
						if(!selectedRowVec.isEmpty()) {
						workDay.add((String)selectedRowVec.get(0));             //  new row ID   !!!!!!!!!!!!!!!!!!!!!!!!
						} //else JOptionPane.showMessageDialog(null,"נא לבחור שורה מתאימה");
						 
						if(vecflag==0||isDateValid((year1)+"-"+(month1)+"-"+(day1)))
						{ 
							workDay.add((year1)+"-"+(month1)+"-"+(day1));               //date
						}
					} catch (BadLocationException e3) {
						// TODO Auto-generated catch block
						e3.printStackTrace();
					}
					 	
					if(!timeEnterTF.getText().isEmpty()){
					workDay.add(timeEnterTF.getText());                          //clock_in
					}
					else {JOptionPane.showMessageDialog(null,"נא לרשום שעת כניסה"); 
					vecflag=1;} //, JOptionPane.WARNING_MESSAGE);
					if(!timeExitTF.getText().isEmpty()){
					workDay.add(timeExitTF.getText());                           //clock_out
					}else {JOptionPane.showMessageDialog(null,"נא לרשום שעת יציאה");
					vecflag=1; 
					}
										  
					  try {
						  if(!timeEnterTF.getText(0, 2).equals("__")){ 
							  int in_hours=Integer.parseInt(timeEnterTF.getText(0, 2));
							  if(in_hours>23||in_hours<0) {JOptionPane.showMessageDialog(null,"שעת כניסה לא תקינה");  vecflag=1;}
								
							  }
						  else { JOptionPane.showMessageDialog(null,"שעת כניסה לא תקינה"); vecflag=1;}
						  if(!timeEnterTF.getText(3, 2).equals("__")){ 
							  int in_minuts=Integer.parseInt(timeEnterTF.getText(3, 2));
							  if(in_minuts>59||in_minuts<0) {JOptionPane.showMessageDialog(null,"דקת כניסה לא תקינה"); vecflag=1;}
								  
						  }
						  else {   vecflag=1;}
						  if(!timeEnterTF.getText(6, 2).equals("__")){ 
							  int in_seconds=Integer.parseInt(timeEnterTF.getText(6, 2));
							  if(in_seconds>59||in_seconds<0) {JOptionPane.showMessageDialog(null,"שנית כניסה לא תקינה"); vecflag=1;}
								  
						  }
						  else {   vecflag=1;}
						  if(!timeExitTF.getText(0, 2).equals("__")){ 
							  int out_hours=Integer.parseInt(timeExitTF.getText(0, 2));
							  if(out_hours>23||out_hours<0) {JOptionPane.showMessageDialog(null,"שעת יציאה לא תקינה"); vecflag=1;}
								
						  }
						  else {JOptionPane.showMessageDialog(null,"שעת יציאה לא תקינה");  vecflag=1;}
						  if(!timeExitTF.getText(3, 2).equals("__")){ 
							  int out_minuts=Integer.parseInt(timeExitTF.getText(3, 2));
							  if(out_minuts>59||out_minuts<0){ JOptionPane.showMessageDialog(null,"דקת יציאה לא תקינה"); vecflag=1;}
								
							  }
						  else {  vecflag=1;}
						  if(!timeExitTF.getText(6, 2).equals("__")){ 
							  int out_seconds=Integer.parseInt(timeExitTF.getText(6, 2));
							  if(out_seconds>59||out_seconds<0){ JOptionPane.showMessageDialog(null,"שנית יציאה לא תקינה"); vecflag=1;}
								 
						  }
						  else {   vecflag=1;}
					 		
					 	 workDay.add(String.valueOf(1));           //flag will send to server.If flag=0 we are doing INSERT work day if flag=1 we are doing UPDATE work day
				 	
						if(!selectedRowVec.equals(null)||selectedRowVec!=null||!selectedRowVec.isEmpty()) 
						    {
							workDay.add(selectedRowVec.get(3)); 
							} else JOptionPane.showMessageDialog(null,"נא לבחור שורה מתאימה");
							
						 
						if (selectedRowVec.get(4).equals("לא בוצעה יציאה"))
						{
							
							workDay.add("null");    
						}
						else  workDay.add(selectedRowVec.get(4)); //lkj
						 
						
					  } catch (BadLocationException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					  
					  if(vecflag!=1)
					  {
						  
						    JLabel goodLbl=new JLabel("כל הנתונים תקינים");
							goodLbl.setFont(new Font("Tahoma", Font.BOLD, 13));
							goodLbl.setForeground(Color.blue);
							checkWorkDayPanel.add(goodLbl); 
							MessageAddOrUpdateWorkingHoursFromDoh msgNewHours= new MessageAddOrUpdateWorkingHoursFromDoh(workDay);
					 
					 try {
							mainMenu.ms.client.sendToServer(msgNewHours);
							MessageSavingReply result=(MessageSavingReply)mainMenu.ms.client.GetMessage();
							
							MessageAddWorkingHoursReply result1 = (MessageAddWorkingHoursReply)mainMenu.ms.client.GetMessage(); 
					        //calculate the work hours of this day and this month
							
							if (result.getResult()==1) //save successful  
							{
						 
								//AccessClockInClockOut access=new AccessClockInClockOut(mainMenu,result1.getWorkHours(),result1.getWorkHours());
								TotalHoursInMonthAccess totHrs = new TotalHoursInMonthAccess(result1.getWorkHours());
							 
							   	 try {
									totHrs.CalculateMonthHours();
								} catch (ParseException e2) {
									// TODO Auto-generated catch block
									e2.printStackTrace();
								}
							   	
							   int totHrsDay=Integer.parseInt(totHrs.getHoursOfMonth());
								if(totHrsDay>12)
						    		
					    		{
									workDay.add("יש חריגה בכמות שעות בתאריך הזה");
					    			 
									JOptionPane.showMessageDialog(null,"יש חריגה בכמות שעות בתאריך הזה"); 
					    		}
					    		else{ workDay.add("null"); }
								 
								if(!workDay.lastElement().equals("null"))          // write comment about exceed number of working hours 
						    		
					    		{
									 
									MessageAddCommentAboutOverHrs mess1 = new MessageAddCommentAboutOverHrs(workDay,0);  
									mess1.setEmpDetails(workDay);      
								 
								    //send to server(empID,data,time) of  employee 
								try {
									mainMenu.ms.client.sendToServer(mess1);
									 
									
								} catch (IOException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
								
								
					    		}
								else if(workDay.lastElement().equals("null")){
									
									MessageRemoveCommentAboutOverHrs mess2 = new MessageRemoveCommentAboutOverHrs(workDay);  
									mess2.setEmpDetails(workDay);       
								 
								    //send to server(empID,data,time) of  employee 
								try {
									mainMenu.ms.client.sendToServer(mess2);
								} catch (IOException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
								}
								
							JLabel goodLbl2=new JLabel("נשמר בהצלחה");
							goodLbl2.setFont(new Font("Tahoma", Font.BOLD, 11));
							goodLbl2.setForeground(Color.blue);
							checkWorkDayPanel.add(goodLbl2);
				 
							MessageShowAllWorkHours msgAllHours=new MessageShowAllWorkHours((String) allHours2.get(0).get(0),( textField_date.getText(5,2)));
						
					
					   mainMenu.ms.client.sendToServer(msgAllHours);
							MessageShowAllWorkHoursReply resultHours=(MessageShowAllWorkHoursReply)mainMenu.ms.client.GetMessage();
						
							Vector<Vector> workHours=resultHours.getEmployeeHours();
							allHours.removeAllElements();
							for(int i=0 ; i<workHours.size();i++)
							{
								allHours.add(workHours.get(i));
							}
						 	tbl.repaint();
							tbl.validate();
						 
							
							//=--------------------------------
							TotalHours.remove(workDayLbl);
							TotalHours.remove(workDaysLbl);
							TotalHours.remove(workDaysLbl2);
							TotalHours.remove(totalHrsLbl);
							TotalHours.add(getTotalHours(allHours));       
							TotalHours.add(getWorkDays2());
							TotalHours.add(getWorkDay(allHours));
							TotalHours.add(getWorkDays());
							
							TotalHours.validate();
							selectedRowVec.removeAllElements();
							savebutt.setEnabled(false);
							mainMenu.getContentPane().validate();
							
														
							}
							else
							{
								JLabel wrongLbl2=new JLabel("בעיית תקשורת . הנתונים לא נשמרו");
								wrongLbl2.setFont(new Font("Tahoma", Font.BOLD, 15));
								wrongLbl2.setForeground(Color.red);
								checkWorkDayPanel.add(wrongLbl2);
							}
													
							
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} 
					 
					 
					     
					 
					 catch (BadLocationException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
										
				}
					  else        //wrong input-print all errors on check_panel
						{
							JLabel wrongLbl=new JLabel("הנתונים אינם תקינים :");
							wrongLbl.setFont(new Font("Tahoma", Font.BOLD, 13));
							wrongLbl.setForeground(Color.red);
							checkWorkDayPanel.add(wrongLbl);
							for(int i=0;i<size;i++)
							{
								JLabel error=new JLabel(checkingResult.get(i));
								error.setForeground(Color.red);
								checkWorkDayPanel.add(error);
							}
							
							addChangeWorkDayPanel();	
							vecflag=0;
						}
					  
				} // check
								
		 
											
				mainMenu.getContentPane().validate();
			}
		});
		
		return btnSave;
	}
	
	/**
	 * Creation CALENDAR
	 * @return
	 */
	private JDatePickerImpl getOrderDate()
	{
	 JDatePickerImpl orderDate = (JDatePickerImpl) JDateComponentFactory.createJDatePicker();
	 orderDate.getModel().setSelected(true);
	 return orderDate;
	}
	
	private Vector <String> inputCheck()
	 {
		 Vector<String> result=new Vector<String>();
		     
		 return result;
		 
	 }
	
	final static String DATE_FORMAT = "yyyy-MM-dd";
	public static boolean isDateValid(String date) 
	{
	 
	        try {
	            DateFormat df = new SimpleDateFormat(DATE_FORMAT);
	            df.setLenient(false);
	            df.parse(date);
	            return true;
	        } catch (ParseException e) {
	        	JOptionPane.showMessageDialog(null,"תאריך לא תקין");
	            return false;
	        }
	}
	
}


